import math

import pandas as pd


def bd09_to_wgs84(lng, lat):
    """百度 BD09 → WGS84（两步转换）"""
    # 1. BD09 → GCJ02
    x_pi = math.pi * 3000.0 / 180.0
    x = lng - 0.0065
    y = lat - 0.006
    z = math.sqrt(x * x + y * y) - 0.00002 * math.sin(y * x_pi)
    theta = math.atan2(y, x) - 0.000003 * math.cos(x * x_pi)
    gcj_lng = z * math.cos(theta)
    gcj_lat = z * math.sin(theta)

    # 2. GCJ02 → WGS84（近似计算）
    ee = 0.00669342162296594323  # 偏心率平方
    a = 6378245.0  # 长半轴

    def transform(lng, lat):
        dlat = transform_lat(lng - 105.0, lat - 35.0)
        dlng = transform_lng(lng - 105.0, lat - 35.0)
        rad_lat = lat / 180.0 * math.pi
        magic = math.sin(rad_lat)
        magic = 1 - ee * magic * magic
        sqrt_magic = math.sqrt(magic)
        dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrt_magic) * math.pi)
        dlng = (dlng * 180.0) / (a / sqrt_magic * math.cos(rad_lat) * math.pi)
        return lng - dlng, lat - dlat

    def transform_lat(x, y):
        ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * math.sqrt(abs(x))
        ret += (20.0 * math.sin(6.0 * x * math.pi) + 20.0 * math.sin(2.0 * x * math.pi)) * 2.0 / 3.0
        ret += (20.0 * math.sin(y * math.pi) + 40.0 * math.sin(y / 3.0 * math.pi)) * 2.0 / 3.0
        ret += (160.0 * math.sin(y / 12.0 * math.pi) + 320 * math.sin(y * math.pi / 30.0)) * 2.0 / 3.0
        return ret

    def transform_lng(x, y):
        ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * math.sqrt(abs(x))
        ret += (20.0 * math.sin(6.0 * x * math.pi) + 20.0 * math.sin(2.0 * x * math.pi)) * 2.0 / 3.0
        ret += (20.0 * math.sin(x * math.pi) + 40.0 * math.sin(x / 3.0 * math.pi)) * 2.0 / 3.0
        ret += (150.0 * math.sin(x / 12.0 * math.pi) + 300.0 * math.sin(x / 30.0 * math.pi)) * 2.0 / 3.0
        return ret

    return transform(gcj_lng, gcj_lat)


df = pd.read_csv('/fttr/全量经纬度2.csv')
df['wgs84经度'], df['wgs84纬度'] = zip(*df.apply(
    lambda row: bd09_to_wgs84(row['中心经度'], row['中心纬度']),
    axis=1
))
df.to_csv('/fttr/全量wgs经纬度.csv', index=False)
